/**
 * Copyright(c) 2013 Jade Techonologies Co., Ltd.
 *
 * History:
 *   13-7-11 下午2:32 Created by sky
 */
package com.jade.modules.message.sms.comm;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.jade.framework.base.comm.ProtocolSession;
import com.jade.framework.base.comm.codec.HeaderLengthCodec;

/**
 * 抽象的编解码器。
 *
 * @author sky
 * @version 1.0 13-7-11 下午2:32
 */
public abstract class AbstractCodec
        extends HeaderLengthCodec
{
    protected SmsConfiguration configuration;

    public void setConfiguration(SmsConfiguration configuration)
    {
        this.configuration = configuration;
    }

    @Override
    public void doEncode(ProtocolSession session, OutputStream os, Object message)
            throws IOException
    {
        DataOutputStream dos = new DataOutputStream(os);
        doEncode((SmsProtocolMessage) message, dos);
    }

    protected abstract void doEncode(SmsProtocolMessage message, DataOutputStream os)
            throws IOException;

    @Override
    public Object doDecode(ProtocolSession session, int length, InputStream in)
            throws IOException
    {
        if (length > configuration.getMaxMessageLength()) {
            throw new IOException("Invalid packet size:" + length);
        }
        return doDecode(new DataInputStream(in), length);
    }

    protected abstract SmsProtocolMessage doDecode(DataInputStream is, int length)
            throws IOException;

//
//    public int getMessageLength(byte[] bytes)
//    {
//        return Binary.toInt(bytes);
//    }
//
//    public SmsProtocolMessage decode(InputStream is)
//            throws IOException, CommException
//    {
//        // read command length
//        DataInputStream dis = new DataInputStream(is);
//        int length = dis.readInt();
//        if (length > configuration.getMaxMessageLength()) {
//            throw new IOException("Invalid packet size:" + length);
//        }
//        return doDecode(dis, length);
//    }

//    public void encode(SmsProtocolMessage message, OutputStream os)
//            throws IOException, CommException
//    {
//        DataOutputStream dos = new DataOutputStream(os);
//        ByteArrayOutputStream bos = new ByteArrayOutputStream(256);
//        DataOutputStream dos1 = new DataOutputStream(bos);
//        doEncode(message, dos1);
//        //write length
//        dos.writeInt(bos.size() + 4);
//        //write pdu
//        bos.writeTo(os);
//        os.flush();
//        bos.close();
//    }
//
}
